package com.security.securityproject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    static final String TARGET_SSID = "\"nf9-11\"";
    static int systembars = 0;
    final Context context = this;
    final Context context2 = this;
    public TextView time;
    private CountDownTimer countDownTimer;
    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            System.out.println("Im in!");

            if (bundle != null) {
                String report = bundle.getString(KeyService.REPORT);
                String password = bundle.getString(KeyService.PASSWORD);
                int duration = bundle.getInt(KeyService.DURATION);
                if (report.equals("ok")) {
                    LayoutInflater factory = LayoutInflater.from(context2);
                    final View textEntryView = factory.inflate(R.layout.resultalertbox, null);
                    AlertDialog.Builder alert = new AlertDialog.Builder(context2);
                    Dialog mDialog = alert.create();
                    final TextView message = (TextView) textEntryView.findViewById(R.id.textView2);
                    final TextView durationview = (TextView) textEntryView.findViewById(R.id.textView3);
                    time= (TextView) textEntryView.findViewById(R.id.textView4);
                    countDownTimer = new MyCountDownTimer(duration*60000, 1000);
                    time.setText(time.getText() + String.valueOf(duration*60000/ 1000));
                    message.setText("\nLogin with you email as username and password: \n\n"+password+"\n");

                    durationview.setText("The remaining duration is : \n");
                    countDownTimer.start();
                    alert.setTitle("Your password is ready");
                    //if(message.getParent()==null){
                    alert.setView(textEntryView);                 //}


                    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                            dialog.dismiss();


                        }
                    });


                    alert.show();



                } else if (report.equals("exist")) {
                    LayoutInflater factory = LayoutInflater.from(context2);
                    final View textEntryView = factory.inflate(R.layout.resultalertbox, null);
                    AlertDialog.Builder alert = new AlertDialog.Builder(context2);
                    Dialog mDialog = alert.create();
                    final TextView message = (TextView) textEntryView.findViewById(R.id.textView2);
                    final TextView durationview = (TextView) textEntryView.findViewById(R.id.textView3);
                    time= (TextView) textEntryView.findViewById(R.id.textView4);
                    countDownTimer = new MyCountDownTimer(duration*60000, 1000);
                    time.setText(time.getText() + String.valueOf(duration*60000/ 1000));
                    message.setText("\n"+password+"\n");
                    alert.setTitle("You already have a password");
                    durationview.setText("The remaining duration is : \n");
                    countDownTimer.start();

                    alert.setView(textEntryView);


                    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                            dialog.dismiss();


                        }
                    });


                    alert.show();

                } else {
                    LayoutInflater factory = LayoutInflater.from(context2);
                    final View textEntryView = factory.inflate(R.layout.resultalertbox, null);
                    AlertDialog.Builder alert = new AlertDialog.Builder(context2);
                    Dialog mDialog = alert.create();
                    final TextView message = (TextView) textEntryView.findViewById(R.id.textView2);
                    final TextView durationview = (TextView) textEntryView.findViewById(R.id.textView3);

                    message.setText(report);
                    durationview.setText("    ");
                    alert.setTitle("Notification");

                    alert.setView(textEntryView);


                    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                            dialog.dismiss();


                        }
                    });


                    alert.show();


                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);


        WifiManager wifimanager = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifimanager.getConnectionInfo();
        System.out.println(wifiInfo.getSSID());
        int linkSpeed = wifimanager.getConnectionInfo().getRssi();
        System.out.println(linkSpeed);


        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        final String device_id = tm.getDeviceId();


        final Intent intent = new Intent(this, RegisterActivity.class);
        final Intent i = new Intent(this, KeyService.class);


        Button b1 = (Button) findViewById(R.id.button1);

        b1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AlertDialog.Builder alert = new AlertDialog.Builder(context);
                Dialog mDialog = alert.create();
                final EditText input = new EditText(context);
                input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

                alert.setTitle("Insert Password");
                if (input.getParent() == null) {
                    alert.setView(input);
                }


                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String value = input.getText().toString().trim();
                        i.putExtra(KeyService.PASSWORD, value);
                        i.putExtra(KeyService.IMEI, device_id);
                        startService(i);


                    }
                });

                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                        dialog.cancel();
                    }
                });

                alert.show();


            }
        });


        Button b2 = (Button) findViewById(R.id.button2);
        b2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(intent);
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();

        registerReceiver(receiver, new IntentFilter(KeyService.NOTIFICATION));
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (!mWifi.isConnected()) {
            connectionAssistant("No WIFI Connection", "You have to be connected to network: ");

        } else {
            WifiManager wifimanager = (WifiManager) getSystemService(WIFI_SERVICE);
            WifiInfo wifiInfo = wifimanager.getConnectionInfo();
            System.out.println(wifiInfo.getSSID());
            if (!wifiInfo.getSSID().equals(TARGET_SSID)) {

                connectionAssistant("Unknown WIFI Network", "You have to be connected to network: ");

            }
        }

    }


    @Override
    protected void onPause()

    {
        super.onPause();


        unregisterReceiver(receiver);


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }


    public void connectionAssistant(String title, String message) {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                this);

        // set title
        alertDialogBuilder.setTitle(title);

        // set dialog message
        alertDialogBuilder
                .setMessage(message + TARGET_SSID)
                .setCancelable(false)
                .setPositiveButton("Connect", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        // dialog.cancel();
                        MainActivity.this.finish();
                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

    }

    public class MyCountDownTimer extends CountDownTimer {
        	  public MyCountDownTimer(long startTime, long interval) {
               super(startTime, interval);
            	  }

                	  @Override
        	  public void onFinish() {
            	   time.setText("Time's up!");
            	  }

                	  @Override
        	  public void onTick(long millisUntilFinished) {
            	   time.setText("" + millisUntilFinished / 1000+ " sec\n");
            	  }
        	 }


}
